#include <iostream>
#include <string>
#include "../Comm/httplib.h"
#include "OJ_Control.hpp"
#include<signal.h>
using namespace httplib;
using namespace control_ns;

Control* controlptr;

void HandlerSignal(int signal)
{
    controlptr->RecoveryMachine();
}

int main()
{
    signal(SIGQUIT,HandlerSignal);//ctrl /
    Server svr;
    Control control;
    controlptr = &control;

    // 1.可以看到首页
    // 2.可以请求所有题目列表 -GET
    // 3.可以看到详细的单个题目 -GET
    // 4.提供判题功能 -POST
    svr.Get("/All_Questions", [&control](const Request &req, Response &resp)
    {
       std::string html;
       control.AllQuestions(&html);
       resp.set_content(html,"text/html; charset=UTF-8"); 
    });

     svr.Get(R"(/Question/(\d+))", [&control](const Request &req, Response &resp)// 正则表达式要加括号,括号表示定义捕获组
     { 
        std::string number = req.matches[1];                                       // 下标[1]存储的是第一个匹配的结果
        std::string html;

        control.OneQuestion(number, &html);
        resp.set_content(html, "text/html; charset=UTF-8");
    });

    svr.Post(R"(/judge/(\d+))", [&control](const Request &req, Response &resp){
        std::string number = req.matches[1];
        std::string out_json;
        std::string in_json = req.body;

        if(!in_json.empty())
        {
            control.Judge(number,in_json,&out_json);
        }
        if(!out_json.empty())
            resp.set_content(out_json,"application/json; charset=UTF-8"); 
        });
    svr.set_base_dir("./wwwroot");
    svr.listen("0.0.0.0", 8080);
    return 0;
}
